package com.dailyblue.java.project.power.interceptor;

import com.dailyblue.java.project.power.bean.Users;
import com.dailyblue.java.project.power.service.RolesService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class HaveRoleInterceptor implements HandlerInterceptor {
    @Resource
    private RolesService rolesService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入了角色校验");
        // 判断用户是否能够访问这个路径
        // 用户所拥有的角色是否可以访问
        // 1. uri
        String uri = request.getRequestURI();
        int index = uri.indexOf("/", 1);
        uri = uri.substring(index);
        // 2. 获取你是谁？
        String token = request.getHeader("token");
        Users user = (Users) request.getSession().getServletContext().getAttribute(token);
        // 3. 判断用户所拥有的角色是否具有访问uri的权限
        int count = rolesService.checkRoleHasPermission(user.getRoleId(), uri);
        // 4. 如果有权限，告诉下一个拦截器不用执行了，没有这个权限，下一个拦截器负责拦截
        if (count == 0) {
            request.setAttribute("AAA", false);
        } else {
            request.setAttribute("AAA", true);
        }
        System.out.println("角色校验是否通过：" + (count >= 1));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
